/*
 * Index.java
 *
 * Created on 18 de julio de 2007, 19:14
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package model;

import java.util.Vector;
import org.w3c.dom.Document;

/**
 *
 * @author mariano
 */
public class Index extends xml.Xmlizable{
    private Vector<Chapter> chapters;
    
    /** Creates a new instance of Index */
    public Index() {
        chapters = new Vector<Chapter>();
    }

    public Vector<Chapter> getChapters() {
        return chapters;
    }

    public void setChapters(Vector<Chapter> chapter) {
        this.chapters = chapter;
    }
    
    public void addChapter( Chapter chapter )
    {
        this.chapters.add( chapter );
    }
    
    public xml.Coleccion toXmlColeccion()
    {
        xml.Coleccion col = new xml.Coleccion( "index" );
        
        for( Chapter chapter: chapters )
        {
            col.addItem( chapter.toXmlColeccion() );
        }
        
        return col;
    }
    
    public static Index fromXml( String str )
    {
        xml.Item col = xml.Item.fromXml( str );
        return parse( col );
    }
    
    public static Index fromXml( Document doc )
    {
        xml.Item col = xml.Item.fromXml( doc.getFirstChild() );
        return parse( col );
    }
    
    private static Index parse( xml.Item col )
    {
        if( !col.isColeccion() || col.getName() != "index" )
            return null;
        
        xml.Coleccion c = (xml.Coleccion)col;
        
        Vector<Chapter> vChapters = new Vector<Chapter>();
        
        for( int i = 0 ; i < c.size() ; i++ )
        {
            xml.Coleccion cChapter = c.getColeccion( i, "chapter" );
            
            if( c == null )
                continue;
            
            vChapters.add( Chapter.fromXml( cChapter.toString() ) );
        }

        return new Index();
    }
    
}
